package erfgame.core.entity.factory;

import java.awt.Dimension;
import java.awt.Point;


import erfgame.core.Dimensions3D;
import erfgame.core.Rotation;
import erfgame.core.entity.AbstractPhysicalEntity;
import erfgame.core.entity.Entity;
import erfgame.core.entity.EntityByTypeFactory;
import erfgame.core.entity.EntityType;
import erfgame.core.graphics.renderer.EntityRenderer;
import erfgame.core.graphics.renderer.Renderer;
import erfgame.core.graphics.renderer.chain.EntityRendererChainFactory;
import erfgame.core.graphics.renderer.chain.RendererChain;
import erfgame.core.world.World;

public class RendererSizingEntityByTypeFactoryProxy implements
		EntityByTypeFactory {
	
	private EntityByTypeFactory proxied;
	private EntityRendererChainFactory rendererFactory;
	
	public RendererSizingEntityByTypeFactoryProxy( EntityByTypeFactory proxied, EntityRendererChainFactory rendererFactory ) {
		this.proxied = proxied;
		this.rendererFactory = rendererFactory;
	}

	public Entity createEntity(World world, EntityType type) {
		Entity entity = this.proxied.createEntity(world, type);
		// TODO : will probably need to look at all renderers from each angle
		RendererChain rendererChain = rendererFactory.getRendererChain(world, entity, Rotation.degrees0);
		EntityRenderer renderer = rendererChain.getHead(); 
		Dimension dimension = renderer.getDimension();
		Point grabPoint = renderer.getGrabPoint();
		int leftWidth = grabPoint.x;
		int rightWidth = dimension.width - grabPoint.x;
		int width;
		if( leftWidth > rightWidth ) {
			width = leftWidth * 2;
		} else {
			width = rightWidth * 2;
		}
		// the grab point isn't always going to be the middle so this isn't always valid
		// pad it out so it is
		Dimensions3D dimensions = new Dimensions3D(
				width, 
				width, 
				dimension.height
		);
		((AbstractPhysicalEntity)entity).setDimensions(dimensions);
		// TODO the size will vary depending upon the state of the entity (and what it is holding, etc...) should make this dynamic somewhere else
		return entity;
	}

}
